#include<iostream>
#include<stdio.h>
#include<stdlib.h>

void toGrey(char* s, unsigned char * buffer, unsigned char * bufferOut, int dimX ,int dimY)
{
    FILE * fin;
    fin=fopen(s,"rb");

    fread(buffer,dimX*dimY*3,1,fin);

    int j=0;

    for(int i=0; i<dimX*dimY*3-3;i+=3)
    {
        bufferOut[j]= buffer[i]*0.299 + buffer[i+1]*0.587 + buffer[i+2]*0.114;
        j++;
    }

    fclose(fin);
}


int main(int argc, char *argv[])
{

    FILE *fileIn, *fileOut, *test;

    if(argc!=6)
    {
        std::cout<<"bledne parametry 0 "<<std::endl;
        exit(0);
    }



    int dimX=atoi(argv[4]);
    int dimY=atoi(argv[5]);

    int delta=atoi(argv[3]);

    int tmp,tmp2=0;

    fileIn=fopen(argv[1],"rb");

    unsigned char *bufferI=(unsigned char *)malloc(dimX*dimY*3*sizeof(unsigned char));

    unsigned char *buffer2=(unsigned char *)malloc(dimX*dimY*1*sizeof(unsigned char));

    unsigned char *bufferOut=(unsigned char *)malloc(dimX*dimY*1*sizeof(unsigned char));


    toGrey(argv[1],bufferI,buffer2, dimX, dimY);

    tmp2=(int)buffer2[0];


    bufferOut[0]=tmp2;


    for(int i=1; i<dimX*dimY*1;++i)
    {
        tmp=(int)buffer2[i]-tmp2;
        if(tmp<=0)
        {
            buffer2[i]=0;
            tmp2-=delta;

        }
        else
        {
            buffer2[i]=1;
            tmp2+=delta;
        }



    }

    for(int i=1; i<dimX*dimY*1;++i)
    {
        if(buffer2[i]==0)
        {
            bufferOut[i]=bufferOut[i-1]-delta;
        }else
        {
            bufferOut[i]=bufferOut[i-1]+delta;
        }
    }
    fileOut=fopen(argv[2],"w");
    fwrite (bufferOut,dimX*dimY*1,1,fileOut);




    return 0;


    fclose(fileOut);
    fclose(fileIn);
    free(bufferI);
    free(buffer2);
    free(bufferOut);

}

